(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.popup.profPastdueViewController', profPastdueViewController);
	profPastdueViewController.$inject = [ '$scope', '$q', '$uibModalInstance', 'Constants', 'dialogsModule', 'gridService', 'modalService', 'layoutConfig' , 'authService', 'ajaxServiceFactory', 'validatorConfig', 'arithService'];
	function profPastdueViewController($scope, $q, $uibModalInstance, Constants, dialogsModule, gridService, modalService, layoutConfig, authService, ajaxServiceFactory, validatorConfig, arithService) {
		var ctrl = this, log = $scope.loggerFactory.getLogger("profPastdueViewController"), ajaxService = ajaxServiceFactory.buildAjaxService({
			getProfPastdueOptions : {
				url : 'do/cda/dataList/profPastdueOptions',
				method : 'post'
			},
		});
		ctrl.dialogsModule = dialogsModule;
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.filterCcys = ctrl.dialogsModule.params.filterCcys || [];
		ctrl.prodSubtypeExtProperty = ctrl.dialogsModule.params.prodSubtypeExtProperty || {};
		ctrl.formName = "profPastdueForm";
		
		ctrl.init = function() {
			ctrl.initSubTableDefine();
			ctrl.initGeneral().then(function() {
				ctrl.profPastdue = ctrl.dialogsModule.params.profPastdue || {};
				ctrl.profPastdueOld = ctrl.dialogsModule.params.profPastdueOld;
				if (ctrl.profPastdueOld) {
					ctrl.profPastdueOld.pastdueSchds = ctrl.profPastdueOld.pastdueSchds || [];
					ctrl.profPastdueOld.tierBaseRateCusts = ctrl.profPastdueOld.tierBaseRateCusts || [];
					ctrl.profPastdueOld.tierBaseRateMixs = ctrl.profPastdueOld.tierBaseRateMixs || [];
				}
				// for base rate customer
				initDataByProfPastdue();
			});
		};
		
		ctrl.initGeneral = function() {
			var defer = $q.defer();
			// init pastdueSchd
			initPastdueSchd();
			// for base rate customer
			initCustTier();
			// for base rate mix
			initMixTier();
			getProfPastdueOptions().then(function(response) {
				ctrl.yesNoOptions = response.yesNoOptions;
				ctrl.ccyOptions = response.ccyOptions;
				ctrl.allIntRateIndexOptions = response.allIntRateIndexOptions;
				ctrl.allocCodeOptions = response.allocCodeOptions;
				ctrl.bufferDaysTypeOptions = response.bufferDaysTypeOptions;
				ctrl.intCalcBasisOptions = filterByProdSubtype("intCalcBasisOptions", response.intCalcBasisOptions);
				ctrl.pastdueIntCatOptions = response.pastdueIntCatOptions;
				ctrl.intRateTypeOptions = filterByProdSubtype("intRateTypeOptions", response.intRateTypeOptions);
				ctrl.allIntBaseTypeOptions = filterByProdSubtype("intBaseTypeOptions", response.intBaseTypeOptions);
				ctrl.intBookTypeOptions = response.intBookTypeOptions;
				ctrl.copyIntBookTypeOptions = angular.copy(response.intBookTypeOptions);
				ctrl.allIntBaseCustomAlgs = response.intBaseCustomAlgOptions;
				ctrl.intOnGraceperdOptions = response.intOnGraceperdOptions;
				defer.resolve();
			}, angular.noop);
			return defer.promise;
		};
		function getProfPastdueOptions() {
			var defer = $q.defer();
			ajaxService.getProfPastdueOptions({}).then(function(response) {
				var profPastdueOptions = {};
				if (response.data) {
					angular.forEach(response.data, function(value, key) {
						var tempValue = {};
						tempValue = value;
						profPastdueOptions[key] = tempValue;
					});
				}
				defer.resolve(profPastdueOptions);
			});
			return defer.promise;
		}
		
		function filterByProdSubtype(type, options) {
			if (!options || options.length == 0) return options;
			var filter;
			if (type == 'intCalcBasisOptions') {
				filter = ctrl.prodSubtypeExtProperty.upIntCalcBases;
				if (!filter) {
					return options;
				}
			} else if (type == 'intRateTypeOptions') {
				filter = ctrl.prodSubtypeExtProperty.upIntRateTypes;
				if (!filter) {
					return options;
				}
			} else if (type == 'intBaseTypeOptions') {
				filter = ctrl.prodSubtypeExtProperty.upIntBaseTypes;
				if (!filter) {
					return options;
				}
			}
			
			var filterOptions = [];
			for (var i = 0; i < options.length; i++) {
				var loadVal = options[i].value;
				if (filter.indexOf(loadVal) >= 0) {
					filterOptions[filterOptions.length] = options[i];
				}
			}
			return filterOptions;
		}
		
		function initDataByProfPastdue() {
			if (ctrl.profPastdue.pastdueSchds) {
				var prePastdueTenor;
				for (var i = 0; i < ctrl.profPastdue.pastdueSchds.length; i++) {
					var pastdueSchd = ctrl.profPastdue.pastdueSchds[i];
					if (i == 0) {
						pastdueSchd.pastdueTenorFrom = 1;
						prePastdueTenor = pastdueSchd.pastdueTenor;
						continue;
					} else {
						pastdueSchd.pastdueTenorFrom = arithService.add(prePastdueTenor, 1);
						prePastdueTenor = pastdueSchd.pastdueTenor;
					}
				}
			}
			
			if (ctrl.profPastdue.tierBaseRateCusts) {
				var preCustTierTenor;
				for (var i = 0; i < ctrl.profPastdue.tierBaseRateCusts.length; i++) {
					var tierBaseRateCust = ctrl.profPastdue.tierBaseRateCusts[i];
					if (i == 0) {
						tierBaseRateCust.tenerFrom = 0;
						preCustTierTenor = tierBaseRateCust.tener;
						continue;
					} else {
//						tierBaseRateCust.tenerFrom = arithService.add(preCustTierTenor, 1);
						tierBaseRateCust.tenerFrom = preCustTierTenor;
						preCustTierTenor = tierBaseRateCust.tener;
					}
				}
			}
		}
		
		ctrl.ccyChanged = function(value) {
			if (ctrl.profPastdue && ctrl.profPastdue.ccy) {
				// filter intRateIndex by ccy
				var intRateIndexOptions = [];
				for (var i = 0; i < ctrl.allIntRateIndexOptions.length; i++) {
					var _intIndex = ctrl.allIntRateIndexOptions[i];
					if (_intIndex.extProperty.ccy == ctrl.profPastdue.ccy) {
						intRateIndexOptions.push(ctrl.allIntRateIndexOptions[i]);
					}
				}
				ctrl.intRateIndexOptions = intRateIndexOptions;
				ctrl.copyIntRateIndexOptions = angular.copy(ctrl.intRateIndexOptions);
				
				resetIntRateIndexByIntBaseType(ctrl);
			}
		};
		
		ctrl.pastdueIntCatOptionsChanged = function(value) {
			if(ctrl.profPastdue.pastdueIntCat == 'P' || ctrl.profPastdue.pastdueIntCat == 'I') {
				var resultOptions = [];
				angular.forEach(ctrl.copyIntBookTypeOptions, function(obj) {
					if (!(obj.value == 'P' || obj.value == 'S')) {
						resultOptions.push(obj);
					}
				});
				ctrl.intBookTypeOptions = resultOptions;
			} else {
				ctrl.intBookTypeOptions = ctrl.copyIntBookTypeOptions;
			}
		};
		
		ctrl.intRateTypeChanged = function(value) {
			if (ctrl.profPastdue.intRateType) {
				// filter intRateIndex by ccy
				var intBaseTypeOptions = [];
				for (var i = 0; i < ctrl.allIntBaseTypeOptions.length; i++) {
					var _intBaseType = ctrl.allIntBaseTypeOptions[i];
					if (ctrl.profPastdue.intRateType == 'V') {
						// if intRateType 'Variable', intBaseType 'Custom' and 'Interpolation' cannot be selected 
						if (!(_intBaseType.value == 'C' || _intBaseType.value == 'I')) {
							intBaseTypeOptions.push(ctrl.allIntBaseTypeOptions[i]);
						}
					} else {
						intBaseTypeOptions.push(ctrl.allIntBaseTypeOptions[i]);
					}
				}
				ctrl.intBaseTypeOptions = intBaseTypeOptions;
			}
		};
		
		ctrl.intBaseTypeChanged = function(value) {
			if (ctrl.profPastdue.intBaseType) {
				resetIntBaseCustomAlgsByIntBaseType(ctrl);
				resetIntRateIndexByIntBaseType(ctrl);
				// need clear
				if (ctrl.profPastdue.intBaseType != 'C') {
					ctrl.profPastdue.tierBaseRateCusts = [];
				}
				// need clear
				if (ctrl.profPastdue.intBaseType != 'M') {
					ctrl.profPastdue.tierBaseRateMixs = [];
				}
			}
		};
		
		function resetIntBaseCustomAlgsByIntBaseType(ctrl) {
			var intBaseCustomAlgData = [];
			for (var i = 0; i < ctrl.allIntBaseCustomAlgs.length; i++) {
				var _intBaseCustomAlg = ctrl.allIntBaseCustomAlgs[i];
				var _filterTypes = _intBaseCustomAlg.extProperty.INT_BASE_TYPES;
				if (_filterTypes && _filterTypes.indexOf(ctrl.profPastdue.intBaseType) >= 0) {
					intBaseCustomAlgData.push(_intBaseCustomAlg);
				}
			}
			ctrl.intBaseCustomAlgs = intBaseCustomAlgData;
		}
		
		function resetIntRateIndexByIntBaseType(ctrl) {
			if (!ctrl.copyIntRateIndexOptions) return;
			var resultData = [];
			var rateIndexValueStr = "";
			if (ctrl.profPastdue.intBaseType == "F") {
				for (var i = 0; i < ctrl.copyIntRateIndexOptions.length; i++) {
					var intRateIndex = ctrl.copyIntRateIndexOptions[i];
					var intIndexObj = intRateIndex.extProperty;
					var intIndexCode = intIndexObj.intIndexCode;
					var dataObj = {};
					dataObj.value = intIndexCode;
					//remove the sitecode, like 'MDBANK:'
					dataObj.label = intIndexCode.substring(intIndexObj.siteCode.length + intIndexObj.ccy.length + 2, intIndexCode.length);
					resultData.push(dataObj);
				}
			} else if (ctrl.profPastdue.intBaseType == "N" || ctrl.profPastdue.intBaseType == "C" || ctrl.profPastdue.intBaseType == "I") {
				for (var i = 0; i < ctrl.copyIntRateIndexOptions.length; i++) {
					var intRateIndex = ctrl.copyIntRateIndexOptions[i];
					var intIndexObj = intRateIndex.extProperty;
					var tenorFlag = intIndexObj.tenorFlag;
					var dataObj = {};
					dataObj.value = intIndexObj.siteCode + ":" + intIndexObj.ccy + ":" + intIndexObj.intIndexName;
					dataObj.label = intIndexObj.intIndexName;
					if(tenorFlag == "Y" && rateIndexValueStr.indexOf(dataObj.value + ",") == -1) {
						rateIndexValueStr += dataObj.value + ",";
						resultData.push(dataObj);
					}
				}
			} else {
				for (var i = 0; i < ctrl.copyIntRateIndexOptions.length; i++) {
					var intRateIndex = ctrl.copyIntRateIndexOptions[i];
					var intIndexObj = intRateIndex.extProperty;
					var intIndexCode = intIndexObj.intIndexCode;
					var dataObj = {};
					dataObj.value = intIndexCode;
					//remove the sitecode, like 'MDBANK:'
					dataObj.label = intIndexCode.substring(intIndexObj.siteCode.length + intIndexObj.ccy.length + 2, intIndexCode.length);
					resultData.push(dataObj);
				}
			}
			ctrl.intRateIndexOptions = resultData;
		}
		
		// this must be out of ajax
		ctrl.initSubTableDefine = function() {
			//init pastdueSchds
			if(ctrl.validatorConfig && ctrl.validatorConfig.profPastdues) ctrl.layoutConfig.formConfigs.pastdueSchd.tableConfigs.table.validatorConfig = ctrl.validatorConfig.profPastdues.pastdueSchds;
			ctrl.pastdueSchdInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.pastdueSchd.tableConfigs.table, ctrlPastdueSchdRowSelectionChanged);
			ctrl.pastdueSchdInnerGridOptions.data = 'vm.profPastdue.pastdueSchds';
			ctrl.pastdueSchdInnerGridOptions.verifyData = 'vm.profPastdueOld.pastdueSchds';
			function ctrlPastdueSchdRowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedPastdueSchds = selectedRows;
			}
			//init tierCriterias
			if(ctrl.validatorConfig && ctrl.validatorConfig.profPastdues) ctrl.layoutConfig.formConfigs.custTier.tableConfigs.table.validatorConfig = ctrl.validatorConfig.profPastdues.tierBaseRateCusts;
			ctrl.custTierInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.custTier.tableConfigs.table, custTierRowSelectionChanged);
			ctrl.custTierInnerGridOptions.data = 'vm.profPastdue.tierBaseRateCusts';
			ctrl.custTierInnerGridOptions.verifyData = 'vm.profPastdueOld.tierBaseRateCusts';
			function custTierRowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedCustTiers = selectedRows;
			}
			//init tierCriterias
			if(ctrl.validatorConfig && ctrl.validatorConfig.profPastdues) ctrl.layoutConfig.formConfigs.mixTier.tableConfigs.table.validatorConfig = ctrl.validatorConfig.profPastdues.tierBaseRateMixs;
			ctrl.mixTierInnerGridOptions = gridService.createInnerGridOptions($scope, ctrl.layoutConfig.formConfigs.mixTier.tableConfigs.table, mixTierRowSelectionChanged);
			ctrl.mixTierInnerGridOptions.data = 'vm.profPastdue.tierBaseRateMixs';
			ctrl.mixTierInnerGridOptions.verifyData = 'vm.profPastdueOld.tierBaseRateMixs';
			function mixTierRowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedMixTiers = selectedRows;
			}
		};
		
		/*******************Pastdue Schedule**********************/
		function initPastdueSchd() {
			ctrl.pastdueTenorChanged = function(rowObj, form, firstLoad) {
				resetPastdueTenorFrom();
			};
			
			function resetPastdueTenorFrom() {
				var pastdueSchdList = ctrl.profPastdue.pastdueSchds, len = pastdueSchdList.length;
				for (var i = 0; i < len; i++) {
					var pastdue = pastdueSchdList[i];
					if (i == 0) {
						pastdue.pastdueTenorFrom = 1;
					}
					if(i<(len-1) && pastdue.pastdueTenor){
						var nextPastdue = pastdueSchdList[i+1];
						nextPastdue.pastdueTenorFrom = arithService.add(pastdue.pastdueTenor, 1);
					}
				}
			}
		}
		/*******************Pastdue Schedule**********************/
		
		/*******************Customer Tier**********************/
		function initCustTier() {
			ctrl.custTierMoreDataDyna = function (obj){
				var params = {};
				// for get dynaparm page
				params.parmSubcat = obj.alg;
				// for data on edit page popup
				params.custDynaparm = {};
				params.custDynaparm.dynamicParams = obj.dynamicParams;
				modalService.openCustomDialogs({
				   'title': 'Cust More Data',
				   'dialogsModule' : 'cda.custdynaparm.popupview',
				   'params': params,
				   'btnCallback' : {
						'ok' : function(resultList) {
							obj.dynamicParams = resultList.dynamicParams;
						}
					}	
				});
			};
			
			ctrl.tenorChanged = function () {
				caculateTenorFrom();
			}
			
			function caculateTenorFrom() {
				var rowDatas = ctrl.profPastdue.tierBaseRateCusts;
				if(rowDatas && rowDatas.length > 0) {
					for(var i = 0; i < rowDatas.length; i++) {
						var preIndex = i - 1;
						if(preIndex >= 0) {
							rowDatas[i].tenerFrom = rowDatas[preIndex].tener;
						} else {
							rowDatas[i].tenerFrom = 0;
						}
					}
				}
			}
		}
		/*******************Customer Tier**********************/
		
		/*******************Mix Tier**********************/
		function initMixTier() {
		}
		/*******************Mix Tier**********************/
		
		ctrl.close = function() {
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback['close'] || dialogsModule.btnCallback['close']() !== false) {
				$uibModalInstance.dismiss();
			}
		};
		
	}
})(angular);
